#include "buzzer.h"
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <QDebug>

Buzzer::Buzzer(int freq, QObject *parent) :
    QObject(parent),fd_buzzer(-1),frequency(freq)
{
    open_buzzer();
    buzzer_timer = new QTimer;
    buzzer_timer->setInterval(40);
    connect( buzzer_timer, SIGNAL(timeout()), this, SLOT(on_time()) );
}

Buzzer::~Buzzer()
{
    close_buzzer();
}

void Buzzer::open_buzzer()
{
    fd_buzzer = open("/dev/pwm", 0);
    if( fd_buzzer < 0 )
    {
        qDebug()<<"open buzzer failed...";
    }
}

void Buzzer::close_buzzer()
{
    if( fd_buzzer >= 0 )
    {
        if ( ioctl( fd_buzzer, PWM_IOCTL_STOP ) < 0 )
        {
            qDebug()<<"close buzzer failed!";
            return;
        }
        if( close(fd_buzzer) == -1 )
        {
            qDebug()<<"close buzzer failed!";
            return;
        }
        fd_buzzer = -1;
    }
}


void Buzzer::start_buzzer()
{
    if( ioctl(fd_buzzer, PWM_IOCTL_SET_FREQ, frequency) < 0 )
    {
        qDebug()<<"start buzzer failed...";
        return;
    }
    buzzer_timer->start();
}

void Buzzer::stop_buzzer()
{
    if( fd_buzzer >= 0 )
    {
        if( ioctl( fd_buzzer, PWM_IOCTL_STOP ) < 0 )
        {
            qDebug()<<"stop buzzer failed!";
            return;
        }
//        if ( ioctl(fd_buzzer, 2) < 0 )
//        {
//            qDebug()<<"ioctl 2:error";
//        }
    }
}

void Buzzer::set_freq(int freq)
{
    if( freq>0 && freq <=20000 )
        frequency = freq;
}

void Buzzer::on_time()
{
    buzzer_timer->stop();
    stop_buzzer();
}
